<template>
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">            
            <el-input v-model="form.role" value="健康管家" disabled />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onSubmit">确认</el-button>
        </el-form-item>
    </el-form>
</template>
<script setup>
import { inject, ref, reactive, watch, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import qs from 'qs'
const emit = defineEmits(['success'])

const axios = inject('axios')
const formRef = ref()
const form = reactive({
    username: '',
    phone: '',
    role: '',
    password: ''
})
const rules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'change' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'change' }],
    password: [{ required: true, message: '请输入密码', trigger: 'change' }]
}
const onReset = () => {
    form.username = ''
    form.phone = ''
    form.role = ''
    form.password = ''
    formRef.value && formRef.value.clearValidate()
}
const onSubmit = () => {
    formRef.value.validate(async valid => {
        if (!valid) return
        form.role = 'caretaker'
        await axios.post('/user/add', qs.stringify(form)).then(() => {}).catch(err => {
            ElMessage.error('新增失败，请稍后重试')
        })
        ElMessage.success('新增成功')
        emit('success')
        onReset()
    })
}
watch(() => form.phone, (val) => {
    if (val && val.length >= 11 && !form.password) {
        form.password = val.slice(-6)
    }
})
</script>
  